<template>
  <div class="admin-container">
    <h1>合作企业管理</h1>

    <!-- 查询和新增按钮放在同一行 -->
    <div class="top-bar">
      <div class="search-container">
        <input
          v-model="searchQuery"
          type="text"
          placeholder="搜索企业名称..."
          class="search-input"
        />      
        <button  @click="findPage">查询</button>
      </div>

      <button class="add-button" @click="openAddModal">新增企业</button>
    </div>

    <!-- 企业列表 -->
    <table>
      <thead>
        <tr>
          <th>企业名称</th>
          <th>企业网址</th>
          <th>企业图片</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="company in companies" :key="company.flid">
          <td>{{ company.flname }}</td>
          <td><a :href="company.flurl" target="_blank">{{ company.flurl }}</a></td>
          <td><img :src="company.flimage" alt="企业图片" class="company-image" /></td>
          <td>
            <button @click="handleDelete(company.flid)"  class="delete-button">删除</button>
          </td>
        </tr>
      </tbody>
    </table>

    <!-- 分页功能 -->
    <el-pagination
          :page-size="params.pageSize"
          :total="params.recordCount"
          v-model:current-page="params.pageNum"
          @current-change="findPage"
           @prev-click="prevPage" 
            @next-click="nextPage"
          layout="total,prev,pager,next"
    />

    <!-- 新增企业弹窗 -->
    <el-dialog title="新增企业" v-model="showModal" width="600px" :center="true" :close-on-click-modal="false" :before-close="handClose">

    <el-form-item label="企业名称" :rules="[{ required: true, message: '请输入企业名称', trigger: 'blur' }]">
      <el-input v-model="form.flname" placeholder="请输入企业名称"></el-input>
    </el-form-item>

    <el-form-item label="企业网址" :rules="[{ required: true, message: '请输入企业网址', trigger: 'blur' }]">
      <el-input v-model="form.flurl" type="url" placeholder="请输入企业网址"></el-input>
    </el-form-item>

    <el-form-item label="上传图片">
      <el-upload
        class="avatar-uploader"
        :show-file-list="false"
        :auto-upload="false"
        :on-change="handleChangeFile"
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
    </el-form-item>

    <span class="dialog-footer">
      <el-button @click="handClose">取消</el-button>
      <el-button type="primary" @click="saveCompany">保存</el-button>
    </span>

</el-dialog>

  </div>
</template>

<script setup>
import { reactive, ref, computed, onMounted } from 'vue'; // 引入onMounted
import { Plus } from '@element-plus/icons-vue';
import { uploadFileReq } from '@/api/File';
import { deleteById, queryPage, insertSave } from '@/api/CorporatePromotion'
import { ElMessageBox, ElMessage } from 'element-plus';
// 企业数据
const companies = ref([]);

// 其他数据定义...
const showModal = ref(false);
let form = ref({});
const searchQuery = ref('');
const params = ref({
  pageNum: 1,
  pageSize: 5,
  recordCount: 0,
  pageCount: 0
});
const currentPage = ref(1);
const imageUrl = ref('');
//删除
function deleteCompany(id){
  console.log(id)
  deleteById(id).then(response => {
    console.log(response);
    searchPage()
  }).catch(error=>{
     console.error('删除失败:', error);
  })
}


const handleDelete = (id) => {
  ElMessageBox.confirm(
    '确定要删除这条企业信息吗？此操作不可恢复！',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(() => {
    // 用户点击确定，执行删除
    deleteCompany(id);
  })
  .catch(() => {
    // 用户点击取消，不做处理
    // 可以添加提示信息，如：ElMessage.info('已取消删除')
  });
};
//分页变化
const findPage=()=>{
searchPage();
}
//分页查询
function searchPage(){

  queryPage(searchQuery.value,params.value.pageNum,params.value.pageSize)
    .then(response => {
      console.log(response);
      companies.value = response.list;
      params.value = response.pager;
    })
    .catch(error => {
      console.error('初始化查询失败:', error);
    });
}
// 页面挂载后执行初始化查询
onMounted(() => {
  // 这里调用queryPage，和组件初始化时执行的效果类似，但时机是在DOM挂载后
    searchPage();
});

// 其他方法...
const openAddModal = () => { showModal.value = true; };
function handClose(){
    showModal.value = false;
  imageUrl.value = '';
  form.value = {};
}
//增加
const saveCompany = () => {
  insertSave(form.value)
    .then(response => {
      console.log(response);
      // 显示成功提示
      ElMessage({
        message: '企业添加成功',
        type: 'success',
        duration: 2000 // 提示信息显示2秒后自动消失
      });
      showModal.value = false;
      searchPage();
    })
    .catch(error => {
      console.error('增加失败:', error);
      // 显示失败提示
      ElMessage({
        message: '企业添加失败，请稍后重试',
        type: 'error',
        duration: 2000
      });
    });
};
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
    params.value.pageNum = currentPage.value;
    searchPage();
  }
};

const nextPage = () => {
  if (currentPage.value <params.value.pageCount ) {
    currentPage.value++;
    params.value.pageNum = currentPage.value;
    searchPage();
  }
};

function handleChangeFile(uploadFile) {
  let file = uploadFile.raw;
  imageUrl.value = URL.createObjectURL(file);
  uploadFileFunc(file);
}

function uploadFileFunc(file) {
  let formData = new FormData();
  formData.append("file", file);
  //  form.value.flimage = "12314";
  uploadFileReq(formData).then(data => {
    form.value.flimage = data;
  });
}
</script>


<style scoped>

/* 关键：固定表格布局，按th设置的宽度渲染 */
table {
  width: 100%;
  margin-top: 20px;
  border-collapse: collapse;
  table-layout: fixed; /* 固定表格布局，核心属性 */
  word-break: break-all; /* 防止英文/数字过长导致列宽异常 */
}

table, th, td {
  border: 1px solid #ccc;
  /* 注意：border-radius 对 table 兼容性差，建议移除或仅用于单元格 */
}

/* 关键：给每列设置固定宽度，总和建议接近100%（可按需调整） */
th {
  padding: 12px;
  text-align: center;
  background-color: #f5f5f5; /* 可选：加背景色区分表头 */
}
/* 按列设置固定宽度（4列分别对应：企业名称、企业网址、企业图片、操作） */
th:nth-child(1) { width: 25%; } /* 企业名称列宽25% */
th:nth-child(2) { width: 40%; } /* 企业网址列宽40%（内容较长，留宽一点） */
th:nth-child(3) { width: 20%; } /* 企业图片列宽20% */
th:nth-child(4) { width: 15%; } /* 操作列宽15% */

/* 关键：控制单元格内容溢出，超长显示省略号 */
td {
  padding: 12px;
  text-align: center;
  white-space: nowrap; /* 禁止内容换行 */
  overflow: hidden; /* 隐藏溢出内容 */
  text-overflow: ellipsis; /* 溢出内容显示省略号 */
}

/* 特殊处理：图片单元格（避免图片拉伸） */
td:nth-child(3) img.company-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  /* 图片容器不继承nowrap，避免影响图片显示 */
  white-space: normal;
}

/* 特殊处理：超链接（企业网址），确保省略号正常显示 */
td:nth-child(2) a {
  display: inline-block; /* 让链接继承单元格宽度限制 */
  width: 100%; /* 链接宽度铺满单元格 */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #007bff; /* 保持链接颜色 */
  text-decoration: none;
}
td:nth-child(2) a:hover {
  text-decoration: underline; /* hover时显示下划线 */
}

.pagination {
  display: flex;
  justify-content: center; /* 水平居中 */
  margin-top: 20px;
  font-size: 14px;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  display: flex;  /* 使用flex布局，确保图片垂直居中 */
  justify-content: center;
  align-items: center;
  height: 180px;  /* 固定高度 */
  width: 180px;  /* 固定宽度 */
  background-color: #f0f0f0;  /* 背景颜色，防止图片太小看不清 */
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  text-align: center;
}

.avatar {
  width: 100%;  /* 确保图片宽度覆盖容器 */
  height: 100%;  /* 确保图片高度覆盖容器 */
  object-fit: cover;  /* 保持图片填充容器并裁剪超出部分 */
  border-radius: 6px;
}

.admin-container {
  width: 80%;
  margin: 0 auto;
  padding: 20px;
  background-color: #f9f9f9;
  font-family: 'Arial', sans-serif;
}

h1 {
  text-align: center;
  font-size: 28px;
  margin-bottom: 20px;
}

.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-container {
  display: flex;
  align-items: center;
}

.search-input {
  padding: 10px;
  width: 250px;
  border-radius: 4px;
  border: 1px solid #ccc;
  font-size: 14px;
  margin-right: 10px;
  transition: all 0.3s ease;
}

.search-input:focus {
  border-color: #007bff;
  box-shadow: 0 0 5px rgba(0, 123, 255, 0.5);
}

.add-button {
  background-color: #007bff;
  color: white;
  padding: 12px 18px;
  border: none;
  cursor: pointer;
  border-radius: 5px;
  font-size: 14px;
  transition: background-color 0.3s ease;
}

.add-button:hover {
  background-color: #0056b3;
}

button {
  background-color: #007bff;
  color: white;
  padding: 10px 12px;
  border: none;
  cursor: pointer;
  margin: 10px;
  border-radius: 5px;
  transition: background-color 0.3s ease;
}

button:hover {
  background-color: #0056b3;
}

table {
  width: 100%;
  margin-top: 20px;
  border-collapse: collapse;
}

table, th, td {
  border: 1px solid #ccc;
  border-radius: 5px;
}

th, td {
  padding: 12px;
  text-align: center;
}

.company-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
}

.delete-button {
  background-color: #dc3545;
  color: white;
  padding: 8px 12px;
  border: none;
  cursor: pointer;
  border-radius: 5px;
  font-size: 14px;
  transition: background-color 0.3s ease;
}

.delete-button:hover {
  background-color: #c82333;
}

.pagination {
  text-align: center;
  margin-top: 20px;
}

.pagination button {
  background-color: #28a745;
  color: white;
  padding: 8px 12px;
  border-radius: 5px;
  font-size: 14px;
  transition: background-color 0.3s ease;
}

.pagination button:disabled {
  background-color: #dcdcdc;
  cursor: not-allowed;
}

.pagination .page-info {
  margin: 0 10px;
  font-size: 16px;
}

.el-dialog__header {
  background-color: #007bff;
  color: white;
}

.el-form-item__label {
  color: #007bff;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
}
</style>



